//
//  NYSubjectListViewController.m
//  NiuWaJiaoYu
//
//  Created by MinLison on 2018/1/11.
//  Copyright © 2018年 niuwaketang. All rights reserved.
//

#import "NYSubjectListViewController.h"
#import "NYSubjectReDoViewController.h"
#import "NYSubjectAnalysisTableViewController.h"
// cells
#import "NYSubjectTitleCell.h"
#import "NYSubjectAnswerCell.h"
#import "NYWrongAnswerTipCell.h"
#import "NYWrongSubjectBookActionCell.h"
#import "NYGoodSubjectActionCell.h"

// views
#import "NYRefreshFooter.h"
#import "BaseTableHeaderFooterView.h"
// requests
#import "NYSubjectListRequest.h"
#import "NYAddToGoodSubjectRequest.h"
#import "NYDelSubjectRequest.h"

@interface NYSubjectListViewController ()<SWTableViewCellDelegate>
@property(nonatomic, strong) NYSubjectListRequest *request;
@end

@implementation NYSubjectListViewController

/// MARK: - Life Cycle
- (instancetype)initWithStyle:(UITableViewStyle)style
{
        return [super initWithStyle:UITableViewStyleGrouped];
}
- (void)viewDidLoad
{
        [super viewDidLoad];
        [self setLoading:YES animation:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
        [super viewWillAppear:animated];
        if (self.isFirstAppear)
        {
                [self loadData];
        }
}
- (void)viewWillDisappear:(BOOL)animated
{
        [super viewWillDisappear:animated];
        [self.tableView.visibleCells enumerateObjectsUsingBlock:^(__kindof UITableViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:[SWTableViewCell class]]) {
                        SWTableViewCell *swCell = (SWTableViewCell *)obj;
                        [swCell hideUtilityButtonsAnimated:YES];
                }
        }];
}
/// MARK: - Data 数据
- (void)reloadData
{
        [self.request clearCache];
        [self loadData];
}

- (void)loadData
{
        [self setLoading:YES animation:YES];
        [self configNimbus];
        self.request = [NYSubjectListRequest requestWithType:self.subjectListType params:nil];
        if (self.category_id != nil) {
                [self.request paramInsert:self.category_id forKey:kRequestKeyCategoryId];
        } else {
                [self.request paramDelForKey:kRequestKeyCategoryId];
        }
        [[self.request pullDown] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NYSubjectListModel * _Nonnull data) {
                [self configNimbusDataForMutableSections:data];
                [self setSuccess];
        } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                [self setError:error];
        }];
}
- (void)setSuccess
{
        [super setSuccess];
        [self configRefreshFooter];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
        });
}
/// MARK: Action
- (void)deleteSubject:(NYSubjectModel *)model atIndexPath:(NSIndexPath *)indexPath
{
        [[NYDelSubjectRequest requestWithType:(NYDelObjectType)(self.subjectListType) param:@{
                                                                                              kRequestKeyWrongQuestionId : model.id
                                                                                              }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof id  _Nonnull data) {
                [NYTipClass showText:request.tipString inView:self.view];
                [self.tableViewModel removeSectionAtIndex:indexPath.section];
                [self.tableView reloadData];
        } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                [NYTipClass showErrorWithText:error.localizedDescription inView:self.view];
                [self readdSectionForTableView:indexPath.section forModel:model];
        }];
}
- (void)readdSectionForTableView:(NSInteger)section forModel:(NYSubjectModel *)model
{
        [self configNimbusSection:section isNew:NO forSubjectObj:model];
        [self.tableView reloadSection:section withRowAnimation:(UITableViewRowAnimationAutomatic)];
}
/// MARK: - TableViewModel Delegate
- (UITableViewCell *)tableViewModel:(NITableViewModel *)tableViewModel cellForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
        @weakify(self);
        UITableViewCell *cell = [super tableViewModel:tableViewModel cellForTableView:tableView atIndexPath:indexPath withObject:object];
        if ([cell isKindOfClass:[SWTableViewCell class]]) {
                SWTableViewCell *swCell = (SWTableViewCell *)cell;
                swCell.delegate = self;
                swCell.rightUtilityButtons = [self rightButtons];
        }
        if ([cell isKindOfClass:[NYWrongSubjectBookActionCell class]]) {
                [(NYWrongSubjectBookActionCell *)cell setActionBlock:^(NYSubjectModel *subjectModel, NYWrongSubjectActionType actionType) {
                        @strongify(self);
                        /// 每组只取第一个
                        NICellObject *cellObj = [self.tableViewModel objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.section]];
                        [self wrongAction:cellObj.userInfo type:actionType];
                }];
        } else if ([cell isKindOfClass:[NYGoodSubjectActionCell class]]) {
                [(NYGoodSubjectActionCell *)cell setActionBlock:^(NYSubjectModel *subjectModel, NYGoodSubjectActionType actionType) {
                        @strongify(self);
                        /// 每组只取第一个
                        NICellObject *cellObj = [self.tableViewModel objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.section]];
                        [self goodAction:cellObj.userInfo type:actionType];
                }];
        }
        return cell;
}

/// MARK: - SWTableViewCell
- (NSArray *)rightButtons
{
        NSMutableArray *rightUtilityButtons = [NSMutableArray new];
        [rightUtilityButtons sw_addUtilityButtonWithColor:
         [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
                                                    title:@"删除"];
        
        return rightUtilityButtons;
}
- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell
{
        return YES;
}
- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
        if (index == 0)
        {
                // Delete button was pressed
                NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
                NICellObject *object = [self.tableViewModel objectAtIndexPath:indexPath];
                [self deleteOjbect:object.userInfo indexPath:indexPath];
        }
}
- (void)deleteOjbect:(NYSubjectModel *)model indexPath:(NSIndexPath *)indexPath
{
        [self deleteSubject:model atIndexPath:indexPath];
        [self.tableViewModel removeObjectsInSection:indexPath.section];
        [self.tableView reloadSection:indexPath.section withRowAnimation:(UITableViewRowAnimationAutomatic)];
}
- (BOOL)swipeableTableViewCell:(SWTableViewCell *)cell canSwipeToState:(SWCellState)state
{
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        if (indexPath.row == 0) {
                return YES;
        }
        return NO;
}
/// MARK: - Action
- (void)wrongAction:(NYSubjectModel *)subjectModel type:(NYWrongSubjectActionType )actionType
{
        if (actionType == NYWrongSubjectActionTypeSeeAnalysis) {
                [self seeAnalysis:subjectModel];
        }
        else if (actionType == NYWrongSubjectActionTypeContinueAnswer)
        {
                [self redo:subjectModel];
        }
        else if (actionType == NYWrongSubjectActionTypeContinueAddToGoodSubject)
        {
                [NYTipClass showLoadingInView:self.view];
                [[NYAddToGoodSubjectRequest requestWithParams:@{
                                                                kRequestKeyExercisesId : NOT_NULL_STRING_DEFAULT_EMPTY(subjectModel.id),
                                                                kRequestKeyTypeID : @(subjectModel.genre),
                                                                }] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NSString * _Nonnull data) {
                        [NYTipClass showText:data inView:self.view];
                } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                        [NYTipClass showErrorWithText:error.localizedDescription inView:self.view];
                }];
        }
}
- (void)goodAction:(NYSubjectModel *)subjectModel type:(NYGoodSubjectActionType)actionType
{
        if (actionType == NYGoodSubjectActionTypeSeeAnalysis) {
                [self seeAnalysis:subjectModel];
        }
        else if (actionType == NYGoodSubjectActionTypeContinueAnswer)
        {
                [self redo:subjectModel];
        }
}
- (void)redo:(NYSubjectModel *)subjectModel
{
        @weakify(self);
        NYSubjectReDoViewController *vc = [[NYSubjectReDoViewController alloc] init];
        vc.subjectModel = subjectModel;
        vc.dismissBlock = ^{
                @strongify(self);
                [self.request clearCache];
                [self loadData];
        };
        [self.navigationController pushViewController:vc animated:YES];
}
- (void)seeAnalysis:(NYSubjectModel *)subjectModel
{
        //                NYSubjectAnalysisTableViewController *vc = [[NYSubjectAnalysisTableViewController alloc] init];
        //                NYSubjectModel *model = subjectModel.modelCopy;
        //                model.indexPath = subjectModel.indexPath;
        //                model.attributeViewHeight = 0;
        //                vc.subjectModel = model;
        //                [self.navigationController pushViewController:vc animated:YES];
        [self routeUrl:kNYSubjectAnalysisURI param:@{
                                                     kRequestKeyType : @(self.subjectListType),
                                                     kRequestKeyTypeID : NOT_NULL_STRING_DEFAULT_EMPTY(subjectModel.id)
                                                     }];
}
/// MARK: - Nimbus
- (void)configNimbus
{
        [super configNimbus];
        [self.tableView registerClass:[BaseTableHeaderFooterView class] forHeaderFooterViewReuseIdentifier:[BaseTableHeaderFooterView className]];
}
- (NSArray <NSIndexPath *>*)configNimbusSection:(NSInteger)section isNew:(BOOL)isNew forSubjectObj:(NYSubjectModel *)subjectObj
{
        NSInteger addToSection = section;
        if (isNew)
        {
                addToSection = [self.tableViewModel addSectionWithTitle:nil].lastIndex;
        }
        NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:subjectObj.exercises_answer_arr.count + 2];
        
        /// 不需要要拷贝模型数据，作为每个题目的记录属性
        [indexPaths addObjectsFromArray:[self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYSubjectTitleCell class] userInfo:subjectObj] toSection:addToSection]];
        if (subjectObj.question_type != NYQuestionTypeFillBlanks) {
                [subjectObj.exercises_answer_arr enumerateObjectsUsingBlock:^(NSString * _Nonnull daanObj, NSUInteger daanIdx, BOOL * _Nonnull daanStop) {
                        [indexPaths addObjectsFromArray:[self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYSubjectAnswerCell class] userInfo:subjectObj] toSection:addToSection]];
                }];
        }
        
        if (self.subjectListType == NYSubjectListTypeWrongSubject)
        {
                [indexPaths addObjectsFromArray:[self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYWrongAnswerTipCell class] userInfo:subjectObj] toSection:addToSection]];
                [indexPaths addObjectsFromArray:[self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYWrongSubjectBookActionCell class] userInfo:subjectObj] toSection:addToSection]];
        }
        else if (self.subjectListType == NYSubjectListTypeGoodSubject)
        {
                [self.tableViewModel addObject:[NICellObject objectWithCellClass:[NYGoodSubjectActionCell class] userInfo:subjectObj.modelCopy]];
        }
        
        return indexPaths;
}
- (void)configNimbusDataForMutableSections:(NYSubjectListModel *)data
{
        [data.list enumerateObjectsUsingBlock:^(NYSubjectModel * _Nonnull subjectObj, NSUInteger subjectIdx, BOOL * _Nonnull subjectStop) {
                [self configNimbusSection:subjectIdx isNew:YES forSubjectObj:subjectObj];
        }];
        [self.tableView reloadData];
}
/// MARK: - tableView delegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        if ([self.tableViewModel countInSection:section] <= 0
            || (self.subjectListType == NYSubjectListTypeWrongSubject && section == 0)
            )
        {
                if (@available(iOS 11, *)) {
                        return CGFLOAT_MIN;
                }
                return 0.0001;
        }
        return __WGHeight(10);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
        if (@available(iOS 11, *)) {
                return CGFLOAT_MIN;
        }
        return 0.0001;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
        BaseTableHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:[BaseTableHeaderFooterView className]];
        view.contentView.backgroundColor = UIColorForBackground;
        return view;
}
/// MARK: - Private
- (void)configRefreshFooter
{
        @weakify(self);
        self.tableView.mj_footer = [NYRefreshFooter footerWithRefreshingBlock:^{
                @strongify(self);
                [[self.request pullUp] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NYSubjectListModel * _Nonnull data) {
                        [self configNimbusDataForMutableSections:data];
                        [self.tableView reloadData];
                        data.list.count == 0 ? [self.tableView.mj_footer endRefreshingWithNoMoreData] : [self.tableView.mj_footer endRefreshing];
                } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }];
        }];
}

/// MAKR: - Super Method
+ (NYViewControllerNavigationBarType)navigationBarType
{
        return NYViewControllerNavigationBarTypeBlue;
}

@end
